package com.base.common.util;

/**
 * 提供了一些静态方法来获取当前和调用类/方法名称。
 *
 * @author admin
 * @date 2020/5/30 PM3:58
 */
public class StackTraceUtil {
    private static final int CLIENT_CODE_STACK_INDEX;

    static {
        int i = 0;
        for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            i++;
            if (ste.getClassName().equals(StackTraceUtil.class.getName())) {
                break;
            }
        }
        CLIENT_CODE_STACK_INDEX = i;
    }

    private StackTraceUtil() {
    }

    public static String getCurrentMethodName() {
        return getCurrentMethodName(1);
    }

    private static String getCurrentMethodName(int offset) {
        return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getMethodName();
    }

    public static String getCurrentClassName() {
        return getCurrentClassName(1);
    }

    private static String getCurrentClassName(int offset) {
        return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getClassName();
    }

    public static String getCurrentFileName() {
        return getCurrentFileName(1);
    }

    private static String getCurrentFileName(int offset) {
        String filename = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getFileName();
        int lineNumber = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX + offset].getLineNumber();

        return filename + ":" + lineNumber;
    }
}
